<template>
	<view class="container">
		<!-- 标题 -->
		<view class="title">
			<!-- <image src="../../static/images/sharePic.png" mode="widthFix" class="title-bg" /> -->
			健康饮食助手
		</view>

		<!-- 回复展示区域 -->
		<view class="response-area">
			<scroll-view scroll-y class="response-scroll">
				<!-- 聊天消息展示 -->
				<view v-for="(item, index) in filteredChatHistory" :key="index" :class="['message-item', item.sender]">
					<view class="message-content">
						{{ item.content }}
					</view>
				</view>

				<!-- 加载状态 -->
				<view v-if="loading" class="loading">正在加载...</view>
				<view v-else-if="noMessages" class="placeholder">暂无消息，请开始对话。</view>
			</scroll-view>
		</view>

		<!-- 输入框和发送按钮 -->
		<view class="input-group">
			<input type="text" placeholder="请输入您的问题..." v-model="userInput" @confirm="sendMessage" />
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
		<!-- 历史记录管理 -->
		<view class="history-actions">
			<button class="clear-history" @click="clearHistory">清除历史记录</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';

	// 数据
	const userInput = ref(''); // 用户输入的问题
	const chatHistory = ref([]); // 聊天历史记录
	const filteredChatHistory = ref([]); // 过滤后的聊天历史记录
	const searchQuery = ref(''); // 搜索关键词
	const loading = ref(false); // 加载状态
	const noMessages = ref(false); // 是否没有消息

	/**
	 * 页面加载时显示机器人开场白
	 */
	onMounted(() => {
		const greetingMessage = "您好！我是您的健康饮食助手，能为您提供各类营养建议，比如食物搭配、营养成分等。请问有什么可以帮助您的吗？";
		chatHistory.value.push({
			sender: 'bot',
			content: greetingMessage
		});
		updateFilteredHistory();
	});

	/**
	 * 调用图灵机器人 API 获取回复
	 * @param {string} msg - 用户输入的消息
	 * @returns {Promise<void>}
	 */
	async function callTuringApi(msg) {
		try {
			// const apiUrl = `https://v2.xxapi.cn/api/turing?msg=${encodeURIComponent(msg)}`;
			const apiUrl =
				`https://api.istero.com/resource/ai/doubao/pro/256k?token=e274977be077797db24669c942ab975b&text=${encodeURIComponent(msg)}`;
			const response = await uni.request({
				url: apiUrl,
				method: "GET",
			});

			// 检查响应数据
			// if (response[1].statusCode === 200 && response[1].data) {
			//     return response[1].data; // 返回解析后的数据
			// } else {
			//     throw new Error("API 响应异常");
			// }
			return response.data
		} catch (error) {
			console.error("调用图灵机器人 API 失败:", error);
			throw new Error("请求失败，请稍后再试");
		}
	}

	/**
	 * 发送消息并获取回复
	 */
	async function sendMessage() {
		const trimmedInput = userInput.value.trim();
		if (!trimmedInput) {
			uni.showToast({
				title: '请输入问题',
				icon: 'none'
			});
			return;
		}

		// 添加用户消息到历史记录
		chatHistory.value.push({
			sender: 'user',
			content: trimmedInput
		});

		try {
			loading.value = true; // 开始加载
			const result = await callTuringApi(trimmedInput);
			// console.log(result);
			// 显示回复
			const botReply = result.text || result.data.answer;
			chatHistory.value.push({
				sender: 'bot',
				content: botReply
			});
		} catch (error) {
			const errorMessage = `请求失败：${error.message}`;
			chatHistory.value.push({
				sender: 'bot',
				content: errorMessage
			});
		} finally {
			loading.value = false; // 结束加载
		}

		userInput.value = ''; // 清空输入框
		updateFilteredHistory(); // 更新过滤后的聊天记录
	}

	/**
	 * 更新过滤后的聊天记录
	 */
	function updateFilteredHistory() {
		if (searchQuery.value.trim()) {
			filteredChatHistory.value = chatHistory.value.filter(item =>
				item.content.toLowerCase().includes(searchQuery.value.toLowerCase())
			);
		} else {
			filteredChatHistory.value = [...chatHistory.value];
		}
		noMessages.value = filteredChatHistory.value.length === 0;
	}

	/**
	 * 清除历史记录
	 */
	function clearHistory() {
		chatHistory.value = [];
		filteredChatHistory.value = [];
		noMessages.value = true;
		uni.showToast({
			title: '历史记录已清除',
			icon: 'success'
		});
	}
</script>

<style scoped>
	/* 全局容器 */
	.container {
		min-height: 100vh;
		width: 100%;
		padding: 40px;
		background-size: cover;
		background-position: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		animation: fadeIn 0.6s ease;

		background-color: #e8f5e9;


	}

	/* 标题 */
	.title {
		position: relative;
		font-size: 48rpx;
		font-weight: bold;
		color: #ffffff;
		text-align: center;
		margin-bottom: 40rpx;
		text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
	}

	.title-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0.3;
		z-index: -1;
	}

	/* 搜索框组 */
	.search-group {
		margin-bottom: 20rpx;
	}

	.search-group input {
		width: 100%;
		height: 80rpx;
		background-color: #ffffff;
		border: 1px solid #e0e0e0;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
	}

	.search-group input:focus {
		border-color: #007aff;
		box-shadow: 0 0 8rpx rgba(0, 122, 255, 0.2);
	}

	/* 回复展示区域 */
	.response-area {
		flex: 1;
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 20rpx;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
		padding: 20rpx;
		overflow: hidden;
	}

	.response-scroll {
		height: 100%;
	}

	/* 聊天消息样式 */
	.message-item {
		margin-bottom: 20rpx;
		padding: 10rpx;
		border-radius: 10rpx;
	}

	.message-item.user {
		background-color: #d1e7dd;
		text-align: right;
	}

	.message-item.bot {
		background-color: #f8d7da;
		text-align: left;
	}

	/* 占位提示 */
	.placeholder {
		font-size: 32rpx;
		color: #999999;
		text-align: center;
		margin-top: 20rpx;
	}

	/* 输入框组 */
	.input-group {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}

	.input-group input {
		flex: 1;
		height: 80rpx;
		background-color: #ffffff;
		border: 1px solid #e0e0e0;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		border-radius: 40rpx;
	}

	.input-group input:focus {
		border-color: #007aff;
		box-shadow: 0 0 8rpx rgba(0, 122, 255, 0.2);
	}

	/* 发送按钮 */
	.send-button {
		width: 160rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #6bbf7a, #06924e);
		color: #ffffff;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 40rpx;
		margin-left: 20rpx;
		border: none;
		box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.send-button:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	/* 历史记录管理 */
	.history-actions {
		margin-top: 20rpx;
		text-align: center;
	}

	.clear-history {
		width: 300rpx;
		height: 80rpx;
		background-color: #e34031;
		color: #ffffff;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 40rpx;
		border: none;
		box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.clear-history:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}
</style>